<?php

Class Catehelp {

    /**
     * TODO 方法已更改。需重新写这个注释
     * 此方法可返回（不限深度的）树状结构的“商品分类”数组。
     * @param int $site_id 站点id（因为是静态方法，所以不宜从$this->site_id读取）
     * @param array $template 商品分类的HTML代码模板。参数结构为：
     * 						array(
     * 							'name'=>'包含{name}标签的HTML代码段',			//这是“分类名称”自身的显示模板，例如:'【{name}】'
     * 							'prefix'=>'一段代码',		//是name的前缀，根据树枝的深度循环复制自身，用以达到缩进的树状显示效果，比如：'&nbsp;'
     * 							'whole'=>'包含{name}和{id}标签的HTML代码段'	//每个树枝公用的HTML代码模板，比如:'<option id="{id}">{name}</option>'
     * 						)
     * @param int $parent 父分类id，一般不需要提供此参数，默认为0（即取得0的后代树）
     * @param int $depth 请不要提供此参数，它只通过方法内部递归赋值
     * @return array 当提供了参数$template时，返回已“HTML化”的分类数组。否则，返回标准的“分类id=>分类名称”数组。
     */
    public static function get_tree($template=array(), $parent = 0, $depth = 0, $sql_array=array(), $edit_id='0') {
        $catalogs = array();

        $children = DB::select(DB::expr($sql_array['id'] . ' AS id,' . $sql_array['name'] . ' AS name'))
                ->from($sql_array['table'])
                ->where('parentid', '=', $parent)
                ->execute();

        if (isset($template['indentation'])) {
            $indentation = str_repeat($template['indentation'], $depth);
        }
        $depth++;


        $children_keys = array();
        foreach ($children as $key => $child) {
            $children_keys[] = $key;
        }

        if (isset($template['last_name_box'])) {
            $children_count = count($children_keys);
            $i = 0;
        }



        foreach ($children_keys as $key => $child_key) {
            $child = $children[$child_key];
            $conditional = $child['id'] == 0 ? FALSE : TRUE;
            if (isset($template['name']) AND $depth > 0) {
                $name_str = $template['name'];
                if ($conditional AND isset($template['conditional_name'])) {
                    $name_str = $template['conditional_name'];
                }
                $replace_name = str_replace('{name}', $child['name'], $name_str);
            } else {
                $replace_name = $child['name'];
            }

            if (isset($template['last_name_box']) AND $i == $children_count - 1) {
                $last_name_box = $template['last_name_box'];
                if ($conditional AND isset($template['last_conditional_name_box'])) {
                    $last_name_box = $template['last_conditional_name_box'];
                }
                $replace_name = str_replace('{name}', $replace_name, $last_name_box);
                $replace_name = str_replace('{id}', $child['id'], $replace_name);
            } elseif (isset($template['name_box'])) {
                $name_box = $template['name_box'];

                if ($conditional AND isset($template['conditional_name_box'])) {
                    $name_box = $template['conditional_name_box'];
                }

                $replace_name = str_replace('{name}', $replace_name, $name_box);
                $replace_name = str_replace('{id}', $child['id'], $replace_name);
                if ($edit_id == $child['id']) {
                    $replace_name = str_replace('{selected}', 'selected="selected"', $replace_name);
                    
                } elseif(is_array($edit_id) && in_array($child['id'], $edit_id))  {
                     $replace_name = str_replace('{checked}', 'checked="checked"', $replace_name);
                }else{
                    $replace_name = str_replace('{checked}', '', $replace_name);
                    $replace_name = str_replace('{selected}', '', $replace_name);
                     
                }
            }
            if (isset($template['indentation'])) {
                $replace_name = str_replace('{indentation}', $indentation, $replace_name);
            }
            if (isset($template['last_name_box']))
                $i++;
            $catalogs[$child['id']]['name'] = $replace_name;

            $catalogs[$child['id']]['children'] = self::get_tree($template, $child['id'], $depth, $sql_array, $edit_id);
        }
        return $catalogs;
    }

    /**
     * TODO 方法已更改。需重新写这个注释
     * 此方法将“商品分类”的树状数组各节点的'name'值连接到一起，成为一个字符串
     * @param array $tree “商品分类”的树状数组
     * @param string $str 请不要提供此参数，它只通过方法内部递归赋值
     * @return string  返回所有商品分类集合而成的字符串
     */
    public static function tree_to_str($tree, $template=array(), $str = '', $is_last = true, $depth = 0) {
        $depth++;
        $count = count($tree);
        if (!$is_last AND $count AND $depth > 1 AND isset($template['parent_box_open'])) {
            $str .= $template['parent_box_open'];
        } elseif ($is_last AND $count AND $depth > 1 AND isset($template['parent_box_last_open'])) {
            $str .= $template['parent_box_last_open'];
        }
        $i = 0;
        $is_last = false;
        foreach ($tree as $id => $branch) {
            if ($i == $count - 1) {
                $is_last = true;
            }
            $str = self::tree_to_str($branch['children'], $template, $str . $branch['name'], $is_last, $depth);
            $i++;
        }
        if ($count AND $depth > 1 AND isset($template['parent_box_close'])) {
            $str .= $template['parent_box_close'];
        }
        return $str;
    }

    /**
     * 返回所给分类的所有祖先分类的id
     * @param int $child_id 分类ID
     * @return array 返回$child_id分类的所有祖先分类的id（不包括家族最顶端的'0'），数组内数据排列方向为：长辈->晚辈
     */
    public static function get_parents($table, $child_id,$id) {
        $parents[] = $child_id;
        $parent_id = $child_id;
        while ($parent_id != 0) {
            $catalog_parent = DB::select('parentid')
                    ->from($table)
                    ->where($id, '=', $parent_id)
                    ->execute();
            $parent_id = $catalog_parent[0]['parentid'];
            if ($parent_id != 0) {
                $parents[] = $parent_id;
            }
        }
        return array_reverse($parents);
    }

    /**
     * 返回所给分了的所有子分类id
     */
    public static function get_childs($parent_id, $table, $table_id) {

        $childs[] = $parent_id;
        $childs_id = $parent_id;
        while ($childs_id != 0) {
            $catalog_child = DB::select(DB::expr($table_id))
                    ->from($table)
                    ->where('chr_parentid', '=', $childs_id)
                    ->execute();

            $childs_id = $catalog_child[0][$table_id];
            $children_keys = array();
            foreach ($catalog_child as $key => $child) {
                $childs[] = $child[$table_id];
            }
        }
        return array_reverse($childs);
    }

    public static function get_left_tree($name_str, $conditional_name_str = null, $sql_array=array(), $edit_id = 0) {
        $catalog_tree_template = array(
            'name_box' => '<li class="catalog_tree_name">' . $name_str . '</li>',
            'last_name_box' => '<li class="catalog_tree_name catalog_tree_last_name">' . $name_str . '</li>',
            'no_conditional' => TRUE
        );
        if ($conditional_name_str !== null) {
            $catalog_tree_template['no_conditional'] = FALSE;
            $catalog_tree_template['conditional_name_box'] = '<li class="catalog_tree_name catelog_tree_conditional_name">' . $conditional_name_str . '</li>';
            $catalog_tree_template['last_conditional_name_box'] = '<li class="catalog_tree_name catalog_tree_last_name catelog_tree_conditional_name">' . $conditional_name_str . '</li>';
        }
        $catalog_str_template = array(
            'parent_box_open' => '<li class="catalog_tree_children"><ol>',
            'parent_box_last_open' => '<li class="catalog_tree_children catalog_tree_last_children"><ol>',
            'parent_box_close' => '</ol></li>'
        );
        return '<ul id="catalog_tree">' . self::tree_to_str(self::get_tree($catalog_tree_template, 0, 0, $sql_array, $edit_id), $catalog_str_template) . '</ul>';
    }

}